package te;

import java.util.ArrayList;
import java.util.List;

/**
 * @author tzp
 * @since 2020/12/20
 */
public class ReverseK {
    public static class ListNode {
        int val;
        ListNode next = null;

        public ListNode(int val) {
            this.val = val;
        }

        @Override
        public String toString() {
            return "ListNode{" +
                    "val=" + val +
                    ", next=" + next +
                    '}';
        }
    }

    public static ListNode reverseLinkedlist(ListNode head, int k) {
        {
            // write code here
            if (head == null || head.next == null || k == 1) return head;

            int l = 0;
            ListNode pre = new ListNode(-1);
            ListNode dummyHead = pre;
            List<ListNode> cache = new ArrayList<>(k);
            while (head != null) {
                if (l == k) {
                    for (int i = cache.size() - 1; i >= 0; i--) {
                        pre.next = cache.get(i);
                        pre = pre.next;
                    }
                    cache.clear();
                    l = 0;
                    pre.next = head;
                }
                System.out.println(head.val);
                cache.add(head);
                l++;
                head = head.next;
            }
            return dummyHead.next;
        }
    }

    public static void main(String[] args) {
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        node1.next = node2;
        node2.next = node3;
        System.out.println(node1);
        System.out.println(reverseLinkedlist(node1, 2));
        System.out.println();
    }
}
